<template>
  <div>
    <el-dialog :visible.sync="addDialogVisibleState" :title="'添加' + title">
      <el-form :model="addData" :rules="formRules" ref="addParamsDialogForm">
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="addData.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <template slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="addProp">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ['sel', 'id'],
  computed: {
    addDialogVisibleState: {
      get() {
        return this.$store.state.params.addDialogVisible
      },
      set() {
        this.$store.commit('params/addDialogVisibleState', false)
      }
    },
    title() {
      return this.sel === 'many' ? '动态参数' : '静态属性'
    }
  },
  data() {
    return {
      addData: {
        attr_name: '',
        attr_sel: this.sel
      },
      formRules: {
        attr_name: [
          {
            required: true,
            message: '请输入动态参数/静态属性!',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    addProp() {
      this.$refs.addParamsDialogForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请填写要添加的属性/参数')
        const { data: res } = await this.$http.post(
          `categories/${this.id}/attributes`,
          { attr_name: this.addData.attr_name, attr_sel: this.sel }
        )

        if (res.meta.status !== 201) return this.$message.error('添加失败！')
        this.$emit('updateList')
        this.closeDialog()
        return this.$message.success('添加成功！')
      })
    },
    closeDialog() {
      this.$store.commit('params/addDialogVisibleState', false)
      this.$refs.addParamsDialogForm.resetFields()
      this.addData.attr_name = ''
    }
  }
}
</script>

<style></style>
